#include "TxAnimation.h"
#include "s3eTimer.h"
#include <limits>
#include <string>
#include "TxResourceManager.h"
#include "../pugixml/pugixml.hpp"
#include <iostream>
#include <sstream>
#include <string>

TxSimpleAnimation* TxSimpleAnimation::createSimpleAnimation(char* file, float rate)
{
	TxSimpleAnimation* newAnimation		= new TxSimpleAnimation();
	newAnimation->frameRate				= rate;
	newAnimation->parseXML(file);
	newAnimation->initialize();
	
	return newAnimation;
}

void TxSimpleAnimation::initialize()
{
	currentFrameNumber	= 0;
	TxDrawingElement::initialize();
	lastFrameTime		= s3eTimerGetUTC();
	isRunning			= true;
	isLooped			= true;
	isReversed			= false;
}

class pugi::xml_document;

void TxSimpleAnimation::parseXML(char* xmlName)
{
	framesTotalNumber	= 0;
	pugi::xml_document xmlFile;
	xmlFile.load_file(xmlName);
	pugi::xml_node framesList	= xmlFile.child("FramesList");
	sprite						= TxResourceManager::getResoureceManager()->addImage(framesList.attribute("image").value());
	for(pugi::xml_node frame = framesList.child("frame"); frame != NULL; frame = frame.next_sibling("frame"))
	{
		int number		= frame.attribute("n").as_int();
		int x			= frame.attribute("x").as_int();
		int y			= frame.attribute("y").as_int();
		int w			= frame.attribute("w").as_int();
		int h			= frame.attribute("h").as_int();
		int deltaX		= frame.attribute("deltaX").as_int();
		int deltaY		= frame.attribute("deltaY").as_int();

		std::pair<CIwFVec2, CIwFVec2> coords(CIwFVec2(x, y), CIwFVec2(w, h));

		frames[number]	= coords;
		delta[number]	= CIwFVec2(deltaX, deltaY);
		framesTotalNumber++;
	}
}

void TxSimpleAnimation::setNextFrame()
{
	if(!isReversed)
	{
		if(++currentFrameNumber == framesTotalNumber)
		{
			currentFrameNumber = 0;
		}
	}
	else
	{
		if(--currentFrameNumber < 0)
		{
			currentFrameNumber = framesTotalNumber;
		}
	}
	lastFrameTime = s3eTimerGetUTC();
}

void TxSimpleAnimation::drawElement()
{
	moveElement();

	if(s3eTimerGetUTC() - lastFrameTime >= 1000 / frameRate)
	{
		setNextFrame();
	}

	Iw2DDrawImageRegion(sprite, position - delta[currentFrameNumber], frames[currentFrameNumber].first, frames[currentFrameNumber].second);

	lastDrawingTime = s3eTimerGetUTC();
}

TxSimpleAnimation::~TxSimpleAnimation()
{
	
}